package ThreadPool;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * @author: lqh
 * @description:
 * @program: Demo
 * @create: 2018-05-23 16:27
 **/
public class test {
    //1.newFixedThreadPool-定长线程池
    //创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。示例代码如下：
    @Test
    public void newFixedThreadPoolTest() {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 5; i++) {
            final int index = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "--" + index);
                }
            });
        }
        executorService.shutdown();
    }

    //2.newCachedThreadPool-缓存线程池
    //线程池为无限大，当执行第二个任务时第一个任务已经完成，会复用执行第一个任务的线程，而不用每次新建线程。
    @Test
    public void newCachedThreadPoolTest() {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            final int index = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "--" + index);
                }
            });
        }
        executorService.shutdown();
    }


    //3.newScheduledThreadPool-定时任务线程池
    //创建一个定长线程池，支持定时及周期性任务执行。延迟执行示例代码如下：
    //(1).延迟执行（延迟3秒执行）
    @Test
    public void newScheduledThreadPool() {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
            for (int i = 1; i <= 10; i++) {
                final int index = i;
                executorService.schedule(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println(Thread.currentThread().getName() + "==" + index);
                    }
                }, 3, TimeUnit.SECONDS);
             }
    }

    //（2）定时执行（延迟3秒后每隔5秒执行）
    @Test
    public void scheduleAtFixedRatePool() {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
        for (int i = 1; i <= 10; i++) {
            final int index = i;
            executorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "==" + index);
                }
            }, 3, 5, TimeUnit.SECONDS);
        }
    }

    //4.newSingleThreadExecutor :单线程线程池，保证按顺序执行
    @Test
    public void test(){
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i=1;i<=10;i++){
            final int index = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "==" + index);
                }
            });
        }
    }

    //ThreadPoolExecuter
    @Test
    public void ThreadPoolExecuterTest() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
        for (int i = 1; i <= 10; i++) {
            final int index = i;
            threadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    threadPoolExecutor.shutdown();
                    System.out.println(Thread.currentThread().getName() + "==" + index);
                    System.out.println("PoolSize:" + threadPoolExecutor.getPoolSize());
                    System.out.println("CorePoolSize:" + threadPoolExecutor.getCorePoolSize());
                    System.out.println("TaskCount:" + threadPoolExecutor.getTaskCount());
                }
            });
        }

    }

    //执行有返回值的线程
    @Test
    public void ThreadPoolResultValue() throws ExecutionException, InterruptedException {
       ExecutorService executorService = Executors.newFixedThreadPool(2);
       for (int i=0;i<100;i++){
           Future<String> task= executorService.submit(new Callable<String>() {
               @Override
               public String call() throws Exception {
                   return  "当前时间："+System.currentTimeMillis();
               }
           });
           String result = task.get();
           System.out.println(result);
       }
    }





}
